import { useReducer, useState } from "react";

export function Counter() {
  // 初始state
  const initialState = { count: -1 };

  // 对初始state进行初始化
  const initialStateFn = (state) => {
    return { count: Math.abs(state.count) };
  };

  // reducer 函数，只有dispatch时才会触发
  const reducer = (state, action) => {
    switch (action.type) {
      case "increment":
        return { count: state.count + 1 };
      case "decrement":
        return { count: state.count - 1 };
      default:
        throw new Error();
    }
  };

  // 在顶层调用 useReducer
  const [state, dispatch] = useReducer(reducer, initialState, initialStateFn);

  return (
    <div>
      <h2>useReducer</h2>
      <p>count: {state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+1</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-1</button>
    </div>
  );
}

export function Challenge1() {
  const initialState = {
    name: "John Doe",
    age: 30,
  };

  const initialStateFn = (state) => {
    return { ...state, name: "Taylor" };
  };

  const reducer = (state, action) => {
    switch (action.type) {
      case "updateName":
        return { ...state, name: action.payload };
      case "updateAge":
        return { ...state, age: action.payload };
      default:
        return state;
    }
  };

  const handleChange = (e) => {
    dispatch({ type: "updateName", payload: e.target.value });
  };

  const handleIncrement = () => {
    dispatch({ type: "updateAge", payload: state.age + 1 });
  };

  const [state, dispatch] = useReducer(reducer, initialState, initialStateFn);

  return (
    <div>
      <input type='text' value={state.name} onChange={handleChange} />
      <p>
        <button onClick={handleIncrement}>Increment age</button>
      </p>
      <p>
        Hello, {state.name}. You are {state.age}.
      </p>
    </div>
  );
}
